package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.ExceptionUtil;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbOrderRecord;
import com.bwie.pojo.TbProdInfo;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.ExceptionUtils;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
* @author 31803
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-07-23 16:47:54
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;

    @Autowired
    HttpServletResponse response;

    @Override
    public R getOrderPage(PageInfoVo pageInfoVo) {
        //构建分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());

        //获取数据
        Page<TbOrder> tbOrderPage = tbOrderMapper.selectOrderPage(page, pageInfoVo);
        List<TbOrder> records = tbOrderPage.getRecords();

        for (TbOrder record : records) {
            ArrayList<String> list = new ArrayList<>();
          List<String> images=  tbOrderMapper.selectImages(record.getOrderId());
          if(images.size()>0&&images!=null){
              for (String image : images) {
                  if(image!=null){
                      List<String> strings = JSON.parseArray(image, String.class);
                      list.addAll(strings);
                  }
              }
          }
          record.setOrderImages(list);

        }



        return R.OK(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R getAddOrder(List<TbProdInfo> tbProdInfos) {

        BigDecimal amountCount = new BigDecimal(0.0);
        StringBuffer name=new StringBuffer();

        //减少库存
        try {
            for (TbProdInfo tbProdInfo : tbProdInfos) {
                TbProdInfo tbProdInfo1 = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if( tbProdInfo1.getProdStock()-tbProdInfo.getBuyNum()<=0){
                   throw new RuntimeException("库存不足");
                }
                tbProdInfo1.setProdStock(tbProdInfo1.getProdStock()-tbProdInfo.getBuyNum());

                tbProdInfoMapper.updateById(tbProdInfo1);
                amountCount.add(amountCount).add(tbProdInfo.getProdPrice().multiply(BigDecimal.valueOf(tbProdInfo.getBuyNum())));
                if(name.length()!=0){
                    name.append(",").append(tbProdInfo.getProdName());
                }else{
                    name.append(tbProdInfo.getProdName());
                }

            }
        } catch (RuntimeException e) {
        return R.ERROR(500,e.getMessage());
        }

        //生成订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderStatus(0);
        long l = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo(String.valueOf(l));
        tbOrder.setOrderType(1);
        tbOrder.setOrderAmount(amountCount);
        tbOrder.setCreateTime(new Date());
        tbOrder.setUserId(1);
        tbOrder.setCreateBy("管理员");
        tbOrder.setProdInfo(String.valueOf(name));
        tbOrder.setPayTime(new Date());
        tbOrderMapper.insert(tbOrder);

        //生成订单明细
        for (TbProdInfo tbProdInfo : tbProdInfos) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();
            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setInfoId(tbProdInfo.getInfoId());
            tbOrderDetail.setBuyNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setCreateBy("管理员");
            tbOrderDetail.setCreateTime(new Date());
            tbOrderDetail.setBuyPrice(tbProdInfo.getProdPrice());
            tbOrderDetailMapper.insert(tbOrderDetail);
        }





        //生成订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setCreateBy("管理员");
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setCreateTime(new Date());
        tbOrderRecord.setOptRecord("添加订单");

        return R.OK();
    }

    @Override
    public R deleteBatchOrder(List<TbOrder> tbOrders) {
        //删除
        for (TbOrder tbOrder : tbOrders) {
            tbOrderMapper.deleteById(tbOrder.getOrderId());
        }
        return R.OK();
    }

    @Override
    public void getExpartList(String ids) {
        if(ids.length()==0||ids==null){
            throw new RuntimeException("请选择数据");
        }
        String[] split = ids.split(",");
        ArrayList<String> list = new ArrayList<>();
        for (String s : split) {
            list.add(s);
        }
        List<TbOrder> tbOrderList = tbOrderMapper.selectBatchIds(list);
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<TbOrder>(TbOrder.class);
        excelUtil.exportExcel(response,tbOrderList,"订单列表","订单列表");
    }
}




